import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:io';

import 'dart:convert';

import '../data.dart';
import 'loading_dialog.dart';

class DioUtil {
  // 工厂模式
  factory DioUtil() =>_getInstance();

  static DioUtil get instance => _getInstance();

  static DioUtil _instance;

  static String _baseUrl="http://49.235.155.72:8088/api";

//  static String _baseUrl="http://192.168.1.107:8088/api";

  static LoadingDialog _loadingDialog;

  int _connectTimeout=7000;

  static Dio _dio;

  static CancelToken _cancelToken;

  DioUtil._internal() {
    // 初始化
    //'Content-Type': 'application/x-www-form-urlencoded'
    BaseOptions options = BaseOptions(
        method: "post",
        receiveTimeout: _connectTimeout,
        headers: {
          HttpHeaders.contentTypeHeader: "application/x-www-form-urlencoded"
        });
    _dio=Dio();
    _dio.options=options;
  }

  static DioUtil _getInstance() {
    if (_instance == null) {
      _instance = new DioUtil._internal();
    }
    return _instance;
  }

  Future<dynamic> post(String url,dynamic data,{bool showDialog:true,bool canCancel:false})async{
    Map<String,dynamic> sendData=Map();
    sendData["s"]=url;
    sendData['k']=StaticValue.token;
    if(data!=null){
      var json = data is Map?jsonEncode(data):data;
      sendData['p']=json;
    }
    if(showDialog){
      showDialogFunction(canCancel);
    }
    print("----sendData----"+sendData.toString());
    Future response= _dio.post(_baseUrl,queryParameters: sendData,cancelToken: _cancelToken)
    .catchError((err){
      print("----networkErr----$err");
        if (CancelToken.isCancel(err)) {
          print('Request canceled! '+ err.message);
        }else{
          // handle error.
        }
    });
    return response.then((onValue){
      closeDialog();
      return response;
    });
  }

  void closeDialog(){
      if(_loadingDialog!=null){
        _loadingDialog.closeDialog();
      }
  }

  void updateLoadingText(String text){
    if(null!=_loadingDialog){
      _loadingDialog.setLoadingText(text);
    }
  }

  void showDialogFunction(bool canCancel,{String loadingText:"正在加载"}){
    if(_loadingDialog==null){
      _loadingDialog=LoadingDialog(
        loadingText: loadingText,
        onCancel: _cancelRequest
      );
    }
    if(canCancel){
      _cancelToken = new CancelToken();
      _loadingDialog.canCancel=canCancel;
    }
    _showLoadingDialog(StaticValue.context);
  }

  void _cancelRequest(){
    _cancelToken.cancel("user cancel");
  }

  _showLoadingDialog(BuildContext context){
    showGeneralDialog(
      context: context,//需要传入一个context
      pageBuilder: (BuildContext buildContext, Animation<double> animation, Animation<double> secondaryAnimation) {
        return SafeArea(
          child: Builder(
              builder: (BuildContext context) {
                return _loadingDialog;
              }
          ),
        );
      },
      //这下面的代码是我从官方源码里复制的
      barrierDismissible: true,
      barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
      barrierColor: Colors.black54,
      transitionDuration: const Duration(milliseconds: 150),
      transitionBuilder: _buildMaterialDialogTransitions,
    );
  }
  //这个方法也是我从官方源码里复制的
  Widget _buildMaterialDialogTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
    return FadeTransition(
      opacity: CurvedAnimation(
        parent: animation,
        curve: Curves.easeOut,
      ),
      child: child,
    );
  }
}